import openpyxl
from django.shortcuts import render,redirect,HttpResponse
from ..models import Device
from django.db.models import Q


import base64


from openpyxl import load_workbook
#导入forms表单
from django import forms

#导入插件
from ..utlis import pagination




def net_dev(request):

    #删除设备,根据网页上传递过来的nid 去数据库中查找并删除
    nid = request.GET.get('nid')
    Device.objects.filter(id=nid).delete()

    #以下实现搜索功能
    data_dict = {}
    search_data = request.GET.get("q",'')

    q1 = Q()
    if search_data:

        q1.connector = 'OR'
        q1.children.append(('ip_address', search_data))
        q1.children.append(('diqu', search_data))
        #data_dict["ip_address__contains"] = search_data

        queryset = Device.objects.filter(q1)
        page_object = pagination.Pagination(request, queryset)
        context = {
            "queryset": page_object.page_queryset,
            "page_string": page_object.html(),
            "search_data": search_data,

        }
        return render(request, "netdev.html", context)
    else:
        #查询所有设备
        queryset = Device.objects.filter(**data_dict)
        page_object = pagination.Pagination(request,queryset)
        context = {
            "queryset":page_object.page_queryset,
            "page_string":page_object.html(),
            "search_data": search_data,

        }
        return render(request,"netdev.html",context)

class DevModeForms(forms.ModelForm):
    # confirm_password = forms.CharField(
    #     label="确认密码",
    #     widget=forms.PasswordInput
    # )


    #定义插件，针对数据库中ip_address在编辑的时候禁止修改
    #ip_address = forms.CharField(disabled=True, label="管理IP")

    class Meta:
        model = Device
        fields = ["ip_address","dev_name","diqu","weizhi","xinghao","username","password","ssh_port"]

        # 定义插件，针对数据库中password字段进行加密
        widgets = {"password": forms.PasswordInput(render_value=True)}  # (render_value=True)如果密码输入不对，加上参数，密码框不会置空}


    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class": "form-control"}


"""添加设备"""
def dev_add(request):
    if request.method == "GET":
        form = DevModeForms()
        return render(request,"devadd.html",{"form":form})


    form = DevModeForms(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/devices/')

    return render(request,"devadd.html",{"form":form})

"""设备编辑"""
def dev_edit(request,nid):
    row_object=Device.objects.filter(id=nid).first()
    if request.method == "GET":
        form = DevModeForms(instance=row_object)
        return render(request,"dev_edit.html",{"form":form})

    form = DevModeForms(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/devices/")
    return render(request,"dev_edit.html",{"form":form})

"""设备登录"""
def dev_ssh(request,nid):
    row_object = Device.objects.filter(id=nid)
    for obj in row_object:
        ip = obj.ip_address
        user = obj.username
        pwd = obj.password
        base_pwd = str(base64.urlsafe_b64encode(pwd.encode("utf-8")),"utf-8")
        return redirect(f"http://127.0.0.1:8888/?hostname={ip}&username={user}&password={base_pwd}")


def dev_all(request):

    if request.method == "POST":
        #1.获取用户上传的文件对象
        file_object = request.FILES.get("exc")

        #2.对象传递给openpyxl之家读取文件内容
        wb = load_workbook(file_object)
        sheet = wb.worksheets[0]

        #3.循环每一行数据
        print(sheet.iter_rows())
        for row in sheet.iter_rows(min_row=2,max_col=8):
            ip = row[0].value
            name = row[1].value
            dq = row[2].value
            wwz = row[3].value
            xh = row[4].value
            un = row[5].value
            pwd = row[6].value
            port = row[7].value
            exists = Device.objects.filter(ip_address=ip).exists()
            if not exists:
                Device.objects.create(ip_address=ip,
                              dev_name=name,
                              diqu=dq,
                              weizhi=wwz,
                              xinghao=xh,
                              username=un,
                              password=pwd,
                              ssh_port=port)
        return redirect('devices')
    return  render(request,"devalladd.html")


def dev_download(request):
    data=["ip_address","dev_name","diqu","weizhi","xinghao","username","password","ssh_port"]

    wb = openpyxl.Workbook()
    ws = wb.active

    ws.append(data)
    filename = 'muban.xlsx'
    wb.save(filename)

    # 打开Excel文件并读取其内容
    with open(filename, 'rb') as file:
        content = file.read()

    # 创建HttpResponse对象并返回
    response = HttpResponse(content, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=' + filename
    return response


class UploadForm(forms.Form):
    ip = forms.CharField(label="管理IP")
    dev_name=forms.CharField(label="设备名称")
    diqu = forms.IntegerField(label="地区")
    weizhi = forms.CharField(label="位置")
    xinghao = forms.CharField(label="型号")
    username = forms.CharField(label="用户名")
    passowrd = forms.CharField(label="密码")
    port = forms.CharField(label="远程端口")
    daoru = forms.FileField(label="请选择文件：")   #制作成上传文件的样式


    bootstrap_exclude_fields = ['daoru']
    def __init__(self, *args, **kwargs):
        super().__init__(*args,**kwargs)  # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            if name in self.bootstrap_exclude_fields:
                continue              #排除某个字段不使用BootStrap样式

            field.widget.attrs = {"class": "form-control"}

# def upload_form(request):
#     title="批量导入"
#     if request.method == "GET":
#         form = UploadForm()
#         return render(request,'upload_form.html',{"title":title,"form":form})
#
#     form = UploadForm(data=request.POST,files=request.FILES)
#     if form.is_valid():
#         #{'daoru': <InMemoryUploadedFile: 上传.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>}
#         #file_object = form.cleaned_data.get("daoru")
#         excel_file = request.FILES['daoru']
#         df = pd.read_excel(excel_file)
#         for index,row in df.iterrows():
#             data=UploadForm(ip_address=row['ip'])
#             print(data)
#         return HttpResponse("....")
#     return render(request, 'upload_form.html', {"title": title, "form": form})

